package com.gobuy.file.controller;

import com.gobuy.common.pojo.Result;
import com.gobuy.common.pojo.StatusCode;
import com.gobuy.file.util.FastDFSClient;
import com.gobuy.file.util.FastDFSFile;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author Gaozexi on 2020/6/3 22:07
 * Step by Step  and Stand on,  You Are The Best Investment!
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file){
        try{
            //文件是否存在
            if(file==null){
                throw new RuntimeException("文件不存在");
            }
            //文件的完整名称
            String originalFilename =  file.getOriginalFilename();
            if(StringUtils.isEmpty(originalFilename)){
                throw new RuntimeException("文件不存在");
            }
            //文件的扩展名称
            String extName = originalFilename.split("\\.")[1];
            //文件内容
            byte[] content = file.getBytes();
            //创建文件上传的封装实体类
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename,content,extName);
            //基于工具类进行文件上传，并接受返回的参数，String[组名，文件完整路径（虚拟磁盘路径+文件二级目录+随机生成的文件名）]
            String[] uploadResult = FastDFSClient.upload(fastDFSFile);
            //封装返回结果
             String url = FastDFSClient.getTrackerUrl() + uploadResult[0] + "/" + uploadResult[1];

            return new Result(true, StatusCode.OK,"文件上传成功",url);

        }catch(Exception e){
         e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR,"文件上传失败");
    }
}
